using System;
using System.Collections.Generic;
using System.Linq;

namespace RFS.BizLogic.PaiShi.Ports.Adapters
{
    public static class ObjectSaverT
    {
        public static IEnumerable<List<T>> Split<T>(this List<T> source, int count)
        {
            if (source == null || source.Count == 0 || count <= 0)
            {
                yield break;
            }

            // Calculate the size of each batch and how many batches will have an extra item.
            int itemsPerBatch = source.Count / count;
            int batchesWithExtra = source.Count % count;

            for (int i = 0; i < count; i++)
            {
                // Determine the number of items in this batch.
                int batchSize = itemsPerBatch + (i < batchesWithExtra ? 1 : 0);
        
                // Take a slice of the list for this batch.
                var batch = source.Skip(i * itemsPerBatch + Math.Min(i, batchesWithExtra)).Take(batchSize).ToList();
        
                yield return batch;
        
                // If we've exhausted the source list, stop yielding.
                if (i >= source.Count - 1) break;
            }
        }
        
        // public static IEnumerable<List<T>> Split<T>(this List<T> source, int count)
        // {
        //     if (source.Count == 0)
        //     {
        //         yield return new List<T>();
        //     }
        //
        //     int currentBatch = 0;
        //     int itemsPerBatch = source.Count / count;
        //     int remainingItems = source.Count % count;
        //
        //     while (currentBatch < count || remainingItems > 0)
        //     {
        //         int take = remainingItems > 0
        //             ? Math.Min(itemsPerBatch + 1, source.Count - currentBatch * itemsPerBatch)
        //             : itemsPerBatch;
        //         yield return source.Skip(currentBatch * itemsPerBatch).Take(take).ToList();
        //         currentBatch++;
        //         remainingItems -= 1;
        //     }
        // }

    }
}